#include "appinc.h"
#include "sans_demo.h"


//demo程序包含2种(2个)配置: param(json格式)、text(字符串口)

char config_param[4096] = TOSTR(
{
	"server": "192.168.1.1:1222",
	"p1": 2,
	"p2": "ap",
	"p3": {
		"p3.1": 1,
		"p3.2": "2-a"
	}
}
);

char config_text[4096] = "demo text config";


static int sans_config_get(void *obj, ssiot_message_t *msg, cJSON *data)
{
	cJSON *sub;
	char *path = "";

	if (data && data->type == cJSON_Object) {
		data = cJSON_GetObjectItem(data, "path");
		if (data && data->valuestring)
			path = data->valuestring;
	}
	LOG_D("getconfig path: %s", path);

	data = cJSON_CreateObject();
	if (data == NULL)
		return -ENOMEM;
	//指定了path时，只获取path的参数
	if (*path == '\0' || !libstr_cmp_prefix(path, "param")) {
		sub = cJSON_Parse(config_param);
		if (sub)
			cJSON_AddItemToObject(data, "param", sub);
	}
	if (*path == '\0' || !libstr_cmp_prefix(path, "text")) {
		cJSON_AddStringToObject(data, "text", config_text);
	}

	//指定了path时，只保留path的参数
	if (*path != '\0')
		json_retian(data, path);
	if (data->child == NULL)
		data->type = cJSON_NULL;
	msg->resp_code = SSCODE_OK;
	msg->resp_data = data;

	return 0;
}



static int sans_config_set(void *obj, ssiot_message_t *msg, cJSON *data)
{
	int ret = 0;
	cJSON *sub;

	if (data == NULL) {
		msg->resp_code = SSCODE_ERR_REQUEST;
		return -EFAULT;
	}
	if (data->type != cJSON_Object)
		return -EFAULT;
	sub = cJSON_GetObjectItem(data, "param");
	if (sub) {
		cJSON *dst = cJSON_Parse(config_param);
		json_merger(dst, sub, false);
		char *str = cJSON_Print(dst);
		strlcpy(config_param, str, sizeof(config_param));
		free(str);
		ret = 0;
	}
	sub = cJSON_GetObjectItem(data, "text");
	if (sub && sub->type == cJSON_String) {
		strlcpy(config_text, sub->valuestring, sizeof(config_text));
		ret = 0;
	}

	msg->resp_code = (ret == 0 ? SSCODE_OK : SSCODE_ERR_SERVER);

	return 0;
}

int sans_config(void *obj, const char *topic, ssiot_message_t *msg)
{
	if (!strcmp(topic, "get"))
		return sans_config_get(obj, msg, msg->data);
	else if (!strcmp(topic, "set"))
		return sans_config_set(obj, msg, msg->data);

	return -EINVAL;
}

